package risk.control.project.service;

import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import risk.control.project.framework.PostService;
import risk.control.project.utils.UUIDUtils;
import risk.control.project.utils.captcha.CaptchaGenerator;

import java.util.HashMap;

/**
 * 验证码
 */
@Service
public class CaptchaService extends PostService {

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public CaptchaService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public HashMap<String, String> getCaptcha() {
        HashMap<String, String> resMap = new HashMap<>();
        //try块退出时，会自动调用res.close()方法，关闭资源。
        try (Jedis jedis = jedisPool.getResource()) {
            SpecCaptcha specCaptcha = CaptchaGenerator.getSpecCaptcha();
            //验证码结果
            String captcha = specCaptcha.text().toLowerCase();
            String imgBase64 = specCaptcha.toBase64("");
            String captchaKey = UUIDUtils.generate();
            //设置保存时间为60秒
            jedis.setex("captcha_key_" + captchaKey, 60, captcha);
            //生成bean
            resMap.put("imgBase64", imgBase64);
            resMap.put("captchaKey", captchaKey);
            return resMap;
        }
    }

    public HashMap<String, String> verify(String captcha, String captchaKey) {
        String key = "captcha_key_" + captchaKey;
        HashMap<String, String> resMap = new HashMap<>();
        try (Jedis jedis = jedisPool.getResource()) {
            //验证码
            boolean exists = jedis.exists(key);
            if (exists) {
                //说明有缓存
                String s = jedis.get(key);
                if (s.equals(captcha)) {
                    //验证码输入正确
                    resMap.put("state", "000");
                    resMap.put("msg", "成功！");
                } else {
                    //验证码输入错误
                    resMap.put("state", "002");
                    resMap.put("msg", "验证码错误！");
                }
            } else {
                //验证码失效
                resMap.put("state", "001");
                resMap.put("msg", "验证码已失效！");
            }
        }
        return resMap;
    }
}
